class HandlerEvent {
	constructor() {
		this.init();
	}

	// 回调函数
	private _handlerFn: any = null;

	private init() {}

	public setHandlerCallback(handlerFn: (event?: any) => void) {
		this._handlerFn = handlerFn;
	}

	/**
	 * 键盘按下事件
	 * @param event
	 */
	private onKeyDownHandle(event: any): void {
		if (event.repeat) return;
		this._handlerFn && this._handlerFn(event);
	}

	/**
	 * 绑定键盘事件
	 */
	public bindKeyboardEvent() {
		const handlerFn = HandlerEvent.debounce(this, 500, this.onKeyDownHandle); // 包装防抖
		window.addEventListener('keydown', handlerFn, false);
	}

	/**
	 * 防抖
	 * @param context
	 * @param delay
	 * @param callback
	 * @returns
	 */
	static debounce(context: any, delay: number, callback: (...args: any[]) => void): any {
		let timer: any = null;
		return function (...innerArgs: any[]) {
			if (timer) {
				clearTimeout(timer);
			}
			timer = setTimeout(() => {
				callback.apply(context || window, innerArgs);
			}, delay);
		};
	}
}

export { HandlerEvent };
